<?php

namespace App\Http\Controllers\Order;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Fee\FeeTypeController;
use App\Http\Validate\Order\Saleorderfee;
use App\Http\Validate\Order\Salesorder;
use App\Http\Validate\Order\Salesordersub;
use App\Models\Custom\Custom;
use App\Models\Fee\FeeType;
use App\Models\Notice\Notice;
use App\Models\Order\Saleimplementation;
use App\Models\Order\Saleimplementationsub;
use App\Models\Order\Saleorder;
use App\Models\Order\Saleorder as ModelSaleorder;
use App\Models\Order\Saleorderfee as ModelSaleorderfee;
use App\Models\Order\Saleordersub as ModelSaleordersub;
use App\Models\Order\SalesCarReport;
use App\Models\Order\Salesorder as ModelSalesorder;
use App\Models\Order\Salesordersub as ModelSalesordersub;
use App\Models\Order\Salesordersubsub as ModelSalesordersubsub;
use App\Models\SaleCover\SaleCover;
use App\Models\Systemparam\Systemparam as ModelSystemparam;
use App\Models\Template\TemplateContractsStamp;
use App\Models\Settle\SettleCompany;
use App\Models\Balance\Balance;
use App\Models\Common\EditLog;
use App\Models\Purchase\PurchaseOrder;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\SnCode;
use App\Services\Common\TableExtFeild;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Stock\Stock;
use Illuminate\Support\Facades\Log;

/**
 * 销货单管理
 */
class SalesorderController extends BaseController
{
    /**
     * 获取表头
     */
    public function gettablefield()
    {
        $cpid = $this->mangerinfo['cpid'];
        $mainextfield = TableExtFeild::getFeildTitle((new ModelSalesorder())->getTable(), $cpid);
        $subextfield = TableExtFeild::getFeildTitle((new ModelSalesordersub())->getTable(), $cpid);
        return response()->json([
            'code' => '000',
            'msg' => '获取成功',
            'data' => [
                'mainextfield' => $mainextfield,
                'subextfield' => $subextfield
            ]
        ]);
    }

    /**
     * 编辑表头字段
     */
    public function changeorderfield(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $sub_order_id = $request->sub_order_id ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $info = ModelSalesorder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => appl])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $suborderinfo = ModelSalesordersub::where(['p_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->first();
        $data = TableExtFeild::getTableFeildData($request);
        if ($suborderinfo) {
            ModelSalesordersub::where(['p_id' => $order_id, 'id' => $sub_order_id, 'is_del' => 1])->update($data);
        } else {
            ModelSalesorder::where(['id' => $order_id, 'manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1])->update($data);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 生成
     * 审核中，删除中订单不能生成
     *
     * 常规订单/锁量不锁规格/保价 发货扣余额
     * 点价订单 发货不扣余额，结算单余额
     * 扣余额(子订单金额)，不入余额记录表 王丹娜 2025.04.24
     *
     *
     *
     */
    public function dopostadd(Request $request)
    {
        $params = [
            'id',
            'order_number',
            'document_date',
            'bill_type',
            'business_type',
            'custom_id',
            'custom_name',
            'settlement_company',
            'wagon_number',
            'driver_phone_number',
            'suborder',
            'otherfee',
            'remark'
        ];
        $req_data = $request->only($params);
        $validate = new Salesorder('add');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $manger_name = $mangerinfo['realname'] ?? 0;

        if (!isset($req_data['otherfee']) || empty($req_data['otherfee']) || !is_array($req_data['otherfee'])) {
            $req_data['otherfee'] = [];
//            return response()->json(['code' => '001', 'msg' => '其他费用必填']);
        }
        $otherfee = is_array($req_data['otherfee']) ? $req_data['otherfee'] : (is_array(json_decode($req_data['otherfee'], true)) ? json_decode($req_data['otherfee'], true) : []);

        $otherfeedata = [];
        $otherfeetotal = 0;
        $ValidateSub = new Saleorderfee('add');
        foreach ($otherfee as $fee) {
            $fee = is_array($fee) ? $fee : json_decode($fee, true);
            if (!$ValidateSub->check($fee)) {
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            $fee_type_info = FeeType::whereIn('cpid', [0, $cpid])->where(['id' => $fee['fee_id'], 'status' => 1, 'is_del' => 1])->first();
            if (!$fee_type_info) {
                return response()->json(['code' => '001', 'msg' => '费用类型参数错误!']);
            }
            $fee['fee_date'] = isset($fee['fee_date']) ? ((strtotime($fee['fee_date']) > 0) ? strtotime($fee['fee_date']) : intval($fee['fee_date'])) : 0;
            if ($fee['fee_date'] < 0) {
                return response()->json(['code' => '001', 'msg' => '费用日期格式错误']);
            }

//            $fee_type_name = [
//                '1' => '销售费用',
//                '2' => '采购费用',
//                '3' => '其他费用',
//            ];
            $fee_type_name = FeeTypeController::$feeTypeCategory;
            $otherfeedata[] = [
                'cpid' => $cpid,
                'fee_type_id' => $fee['fee_type_id'],
                'fee_type_name' => $fee_type_name[$fee['fee_type_id']],
                'fee_date' => $fee['fee_date'],
                'fee_id' => $fee['fee_id'],
                'fee_name' => $fee_type_info->type_name,
                'company_name' => $fee['company_name'],
                'company_id' => $fee['company_id'],
                'price' => mathfuncmoney('mul', $fee['price'], 100),
                'total_price' => mathfuncmoney('mul', $fee['total_price'], 100),
                'settlement_price' => mathfuncmoney('mul', $fee['settlement_price'], 100),
                'remark' => isset($fee['remark']) ? strval($fee['remark']) : '',
            ];
            $otherfeetotal = $otherfeetotal + $fee['price'];
        }

        // $balance = Balance::where(['custom_id' => $req_data['custom_id']])->first()->toArray();
        // if ($balance['balance'] < 0) {
        //     return response()->json(['code' => '001', 'msg' => '客户余额不足，不能生成']);
        // }

        $sale_id = $req_data['id'];
        $sale = ModelSaleorder::where('id', $sale_id)->first();
        if (!$sale) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            $sale = $sale->toArray();
        }

        if (in_array($sale['del_status'],[2,3])) {
            if($sale['del_status'] == 2){
                return response()->json(['code' => '001', 'msg' => '订单删除审核中，不能生成']);
            }
            if($sale['del_status'] == 3){
                return response()->json(['code' => '001', 'msg' => '订单已删除，不能生成']);
            }
        }

        if ($sale['examine_status'] == 4) {
            return response()->json(['code' => '001', 'msg' => '低于指导价审核被驳回，不能生成']);
        }

        if ($sale['examine_status'] == 2) {
            return response()->json(['code' => '001', 'msg' => '低于指导价审核中，不能生成']);
        }

        if($sale['is_sys_purchase'] == 2) {
            $purchaseOrder = PurchaseOrder::where('sale_order_number', $sale['order_number'])->first();
            if ($purchaseOrder && $purchaseOrder->is_finish == 1) {
                return response()->json(['code' => '001', 'msg' => '自采订单没有完成采购流程，请稍等！']);
            }
        }

        if(!in_array($sale['order_status'],['1','3'])) {
            return response()->json(['code' => '001', 'msg' => '订单未审核，请稍等！']);
        }

        $suborder = $req_data['suborder'];
        if (!is_array($suborder)) {
            $suborder = json_decode($suborder, true);
            if (!is_array($suborder)) {
                return response()->json(['code' => '001', 'msg' => '子订单数据格式错误']);
            }
        }


        $custom_info = Balance::where('custom_id', $req_data['custom_id'])->first()->toArray();
        $order_total = 0;
        foreach ($suborder as $item) {
            if(!isset($item['id'])){
                return response()->json(['code' => '001', 'msg' => '子订单id不存在']);
            }
            $sale_sub_one = ModelSaleordersub::where('id', $item['id'])->first();
            if (!$sale_sub_one) {
                return response()->json(['code' => '001', 'msg' => '子订单不存在']);
            }
            $sale_sub_one = $sale_sub_one->toArray();
            if ($sale_sub_one['produce_status'] == config('constants.produce_status.produced')) {
                return response()->json(['code' => '001', 'msg' => '已生成子订单不能生成']);
            }

            if ($sale_sub_one['examine_status'] == config('constants.examine_status.in_review')) {
                return response()->json(['code' => '001', 'msg' => '审核中子订单不能生成']);
            }

            if ($sale['order_type'] == 2) {
                if (empty($item['archive_spec'])) {
                    return response()->json(['code' => '001', 'msg' => '锁量不锁规格订单生成的时候需要选择规格']);
                }
            }
            /***
             *  发货单校验 订单子数据 件数，重量，单价
             *
            */
            $pieces = $item['pieces']??0;
            $unit_price_cent = mathfuncmoney('mul', $item['unit_price'], 100);
            $total_weight_g = mathfuncweight('mul', $item['total_weight'] ?? 0, 10000);

            $SaleorderController = new SaleorderController($request);
            $res_check_suborder_item = $SaleorderController->checkSubOrderItem('SalesOrder',$req_data,$item,$total_weight_g,$unit_price_cent,$pieces);
            if($res_check_suborder_item['code'] != '000'){
                return response()->json($res_check_suborder_item);
            }
            /****
             *  自采订单，发货需要验库存 可用件数/可用重量 2025.06.18
             *
             *
            */



            //$order_total += $sale_sub_one['total'];
            $order_total += mathfuncmoney('mul',$item['total'],100,2);
        }

        //if($sale['order_type'] != '4'){
        if ($custom_info['balance'] < $order_total ) {
            return response()->json(['code' => '001', 'msg' => '客户余额不足，不能生成']);
        }
        //}


        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;
        $manger_id = $mangerinfo['id'] ?? 0;
        $manger_name = $mangerinfo['realname'] ?? '';

//        $one = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'company_costs'])->first();
//        if ($one) {
//            $companycosts = $one->value;
//        } else {
//            $companycosts = 10;
//        }

        $subvalidate = new Salesordersub('add');
        foreach ($suborder as $item) {
            if (!$subvalidate->check($item)) {
                return response()->json(['code' => '001', 'msg' => $subvalidate->getError()]);
            }
        }

        $settle_company_id = SettleCompany::where([
            ['settle_company_name', '=', $req_data['settlement_company']],
            ['cpid', '=', $cpid],
        ])->value('id');
        DB::beginTransaction();
        try {
            /**
             *  扣库存 单位：g
             *
             *  点价订单，审核通过后，扣除库存;
             *
             *  低于指导价审核，如果订单触发，在创建订单时不锁库存，审核通过才锁库存。2025.05.22
             *
             *  锁量不锁规格（虚拟订单）创建发货单时，才确定真实钢材；此时扣库存，2025.07.08
             *
             *
             */
            if($sale['order_type'] == '2'){
                $salesorder_decrStock = $SaleorderController->incrDecrStockInSaleEdit($req_data['suborder'],'decr');
                if($salesorder_decrStock['code']!='000'){
                    return response()->json($salesorder_decrStock);
                }
            }


            $data = [
                'cpid' => $cpid,
                'manger_id' => $manger_id,
                'manger_name' => $manger_name,
                'order_number' => $req_data['order_number'],
                'document_number' => SnCode::getSnCode('XH_'),
                'document_date' => $req_data['document_date'],
                'bill_type' => $req_data['bill_type'],
                'business_type' => $req_data['business_type'],
                'custom_id' => $req_data['custom_id'],
                'custom_name' => $req_data['custom_name'],
                'settlement_company' => $req_data['settlement_company'] ?? '',
                'settle_company_id' => $settle_company_id,
                'wagon_number' => $req_data['wagon_number'],
                'driver_phone_number' => $req_data['driver_phone_number'],
                'remark' =>$req_data['remark'],
                'create_at' => time(),
            ];

            $p_id = ModelSalesorder::create($data)->id;

            foreach ($otherfeedata as $key => $item) {
                $otherfeedata[$key]['order_number'] = $sale['order_number'];
                $otherfeedata[$key]['sales_id'] = $p_id;
                $other_pid = ModelSaleorderfee::create($otherfeedata[$key])->id;

                ModelSaleorderfee::where('id', $other_pid)->update([
                    'other_pid' => $other_pid,
                ]);
            }

            $sales_weight = $sales_amount = $sales_pieces = 0;
            foreach ($suborder as $key => $item) {
                $sale_order_sub = ModelSaleordersub::where('id', $item['id'])->first();
                if (!$sale_order_sub) {
                    return response()->json(['code' => '001', 'msg' => '子订单不存在']);
                }
                /****
                 *  增加自采订单，校验库存 可用件数/可用重量 > 0, 自采订单场景，提前扣除库存,判定库存量>0
                 *
                 *
                 */
                if($sale_order_sub['is_sys_purchase'] == 2){
                    $stock = Stock::where(['id' => $sale_order_sub['stock_id']])->first();
                    if ($stock) {
                        $stock = $stock->toArray();
                        if ($stock['can_use_pieces'] < 0) {
                            return response()->json(['code' => '001', 'msg' => '库存件数不足']);
                        }
                        if($stock['can_use_weight'] < 0){
                            return response()->json(['code' => '001', 'msg' => '库存重量不足']);
                        }
                    } else {
                        return response()->json(['code' => '001', 'msg' => '库存不存在']);
                    }
                }
                /***
                 *  判断当前订单是否虚拟订单生成发货单 2025.04.08
                 *  订单选择的虚拟的钢材不需要在发货单展示，订单不需要展示根据虚拟钢材选择的非虚拟的钢材 王丹娜 2025.04.08
                 *
                 *
                */

                $sale_order_sub = $sale_order_sub->toArray();
                if($sale_order_sub['archive_type'] != '4'){
                    $pieces = $sale_order_sub['pieces'] - $sale_order_sub['produce_pieces'];
                    //当前销售子订单件数
                    if ($item['pieces'] < $pieces) {
                        ModelSaleordersub::where('id', $sale_order_sub['id'])->update([
                            'produce_pieces' => $item['pieces'] + $sale_order_sub['produce_pieces'],
                            'produce_status' => config('constants.produce_status.produceing'),
                            'update_at' => time(),
                        ]);
                    } elseif ($item['pieces'] == $pieces) {
                        ModelSaleordersub::where('id', $sale_order_sub['id'])->update([
                            'produce_pieces' => $item['pieces'] + $sale_order_sub['produce_pieces'],
                            'produce_status' => config('constants.produce_status.produced'),
                            'update_at' => time(),
                        ]);
                    } else {
                        return response()->json(['code' => '001', 'msg' => '子订单可生成件数不足，不是库存件数不足']);
                    }


                    $total_weight = $sale_order_sub['total_weight'] - $sale_order_sub['produce_total_weight'];
                    //如果当前销售子订单总重量小于等于总重量
                    $item_total_weight = mathfuncweight('mul', $item['total_weight'], 10000);
                    if ($item_total_weight <= $total_weight) {
                        //正常发货
                        ModelSaleordersub::where('id', $sale_order_sub['id'])->update([
                            'produce_total_weight' => $item_total_weight + $sale_order_sub['produce_total_weight'],
                        ]);
                    } else {
                        //查询可以用的库存  如果可用库存足够 需要吧多出来的重量从可用迁移到已锁  如果可用不够 则拦截提示
                        //使用db查询  应为model中吧计算的值除以10了 导致计算结果不对
                        $stock = Db::table('stock')->where(['id' => $item['stock_id']])->first();
                        //需要从可用迁移的数量
                        $qianyi_total_weight = $item_total_weight - $total_weight;
                        if ($stock->can_use_weight < $qianyi_total_weight) {
                            return response()->json(['code' => '001', 'msg' => '库存总重量不足']);
                        }
                        $stock_lock_weight = $stock->locked_weight + $qianyi_total_weight;
                        $can_use_weight = $stock->can_use_weight - $qianyi_total_weight;
                        Stock::where(['id' => $item['stock_id']])->update([
                            'locked_weight' => $stock_lock_weight,
                            'can_use_weight' => $can_use_weight,
                        ]);
                        ModelSaleordersub::where('id', $sale_order_sub['id'])->update([
                            'produce_total_weight' => $item_total_weight + $sale_order_sub['produce_total_weight'],
                        ]);

                    }
                }else{
                    //虚拟订单 发货，标记为 生成中
                    ModelSaleordersub::where('id', $sale_order_sub['id'])->update([
                        'produce_pieces' => $item['pieces'] + $sale_order_sub['produce_pieces'],
                        'produce_status' => config('constants.produce_status.produceing'),
                        'update_at' => time(),
                    ]);
                }


                $unit_price = mathfuncmoney('mul', $item['unit_price'], 100);
                $guiding_price = $sale_order_sub['guiding_price'];



                // if ($item['is_sys_purchase'] == 2) {

                // } else {
                //     $accrual = $unit_price - $guiding_price + $companycosts;
                //     $performance = $accrual * mathfuncweight('mul', $item['total_weight'] ?? 0, 10000) - $otherfeetotal;
                // }

                $suborder = isset($item['suborder']) ? (is_array($item['suborder']) ? $item['suborder'] : (is_array(json_decode($item['suborder'], true)) ? json_decode($item['suborder'], true) : [])) : [];

                $pieces = $item['pieces'] ?? 0;
                $data_sub_item[$key]['sale_id'] = $item['id'];
                $data_sub_item[$key]['cpid'] = $cpid;
                $data_sub_item[$key]['p_id'] = $p_id;
                $data_sub_item[$key]['manger_id'] = $manger_id;
                $data_sub_item[$key]['material_id'] = $item['material_id'];
                $data_sub_item[$key]['stock_id'] = $item['stock_id'];
                $data_sub_item[$key]['archive_no'] = $item['archive_no'];
                $data_sub_item[$key]['warehouse_name'] = $item['warehouse_name'];
                $data_sub_item[$key]['steel_factory_name'] = $item['steel_factory_name'];
                $data_sub_item[$key]['archive_type'] = $item['archive_type'];
                $data_sub_item[$key]['archive_name'] = $item['archive_name'];
                $data_sub_item[$key]['archive_spec'] = $item['archive_spec'];
                $data_sub_item[$key]['archive_material'] = $item['archive_material'];
                $data_sub_item[$key]['breed_name'] = $item['breed_name'];
                $data_sub_item[$key]['weight'] = mathfuncweight('mul', $item['total_weight'], 10000);
                $data_sub_item[$key]['pieces'] = $pieces;
                $data_sub_item[$key]['length'] = $item['length'] ?? 0;
                $data_sub_item[$key]['unit_price'] = $unit_price;
                $data_sub_item[$key]['guiding_price'] = $guiding_price;
                $data_sub_item[$key]['total'] = mathfuncmoney('mul', $item['total'], 100);
                $data_sub_item[$key]['accrual'] = mathfuncmoney('mul', $item['accrual'], 100);
                $data_sub_item[$key]['accrual_status'] = $item['accrual_status'];
                $data_sub_item[$key]['performance'] = mathfuncmoney('mul', $item['performance'], 100);
                $data_sub_item[$key]['is_sys_purchase'] = $item['is_sys_purchase'];
                $data_sub_item[$key]['suborder'] = json_encode($suborder, true);
                $data_sub_item[$key]['remark'] = $item['remark'];
                $data_sub_item[$key]['create_at'] = time();
                $data_sub_item[$key]['qianyi_total_weight'] = $qianyi_total_weight ?? 0;

                $sales_weight = $sales_weight + mathfuncweight('mul', $item['total_weight'], 10000);
                $sales_amount = $sales_amount + mathfuncweight('mul', $item['total'], 100);
                $sales_pieces = $sales_pieces + $pieces;

            }

            $sales_total = 0;
            foreach ($data_sub_item as $item) {
                $sales_id = ModelSalesordersub::create($item)->id;
                Saleimplementationsub::where([
                    'cpid' => $cpid,
                    'sale_id' => $item['sale_id'],
                ])->update([
                    'sales_id' => $sales_id,
                    'sales_weight' => DB::raw('sales_weight + ' . $item['weight']),
                    'sales_amount' => DB::raw('sales_amount + ' . $item['total']),
                    'sales_pieces' => DB::raw('sales_pieces + ' . $item['pieces']),
                    'update_at' => time()
                ]);

                $item['suborder'] = json_decode($item['suborder'], true);
                if (!empty($item['suborder'])) {
                    foreach ($item['suborder'] as $suborder) {
                        $data_sub_sub_item = [
                            'cpid' => $cpid,
                            'p_id' => $sales_id,
                            'manger_id' => $manger_id,
                            'create_at' => time()
                        ] + $suborder;
                        ModelSalesordersubsub::create($data_sub_sub_item);
                    }
                }

                $sales_total = $sales_total + $item['total'];
            }
            /**
             * 销售订单生成是否完成,需要比较销售订单和销售发货单 2025.03.14
             * 发货单有删除
            */
            $data = [
                'produce_status' => 2,
                'update_at' => time()
            ];
            $finish = $this->checkDelivery($req_data);//检测销售订单发货是否完成
            if($finish){
                $data = [
                    'produce_status' => 3,
                    'update_at' => time()
                ];
            }
            ModelSaleorder::where('id', $sale_id)->update($data);
            Saleimplementation::where('order_number', $req_data['order_number'])->update([
                'sales_weight' => DB::raw('sales_weight + ' . $sales_weight),
                'sales_amount' => DB::raw('sales_amount + ' . $sales_amount),
                'sales_pieces' => DB::raw('sales_pieces + ' . $sales_pieces)
            ]);

            /***
             *  扣除客户余额，点价（后结算模式），以销售结算单（T+销售发票）金额为准，释放
             *
             *
            */
            if($sale['order_type'] != '4'){
                Balance::where(['custom_id' => $req_data['custom_id'],'cpid' => $cpid])->update([
                    'balance' => DB::raw('balance - ' . $sales_total)
                ]);
            }


            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '销货单添加失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 列表
     */
    public function getlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = ModelSalesorder::getList($request, $memberinfo, $isgetall);
        if ($list['list']) foreach ($list['list'] as $key => $value) {
            foreach ($value['suborder'] as $k => $v) {
                $list['list'][$key]['suborder'][$k]['weight'] = mathfuncweight('div', $v['weight'], 10000, 4);
                $list['list'][$key]['suborder'][$k]['unit_price'] = mathfuncmoney('div', $v['unit_price'], 100, 2);
                $list['list'][$key]['suborder'][$k]['total'] = mathfuncmoney('div', $v['total'], 100, 2);

                $list['list'][$key]['suborder'][$k]['diff'] = mathfuncmoney('div', $v['diff'] ?? 0, 100, 2);
                $list['list'][$key]['suborder'][$k]['accrual'] = mathfuncmoney('div', $v['accrual'], 100, 2);
                $list['list'][$key]['suborder'][$k]['performance'] = mathfuncmoney('div', $v['performance'], 100, 2);

                $suborder = ModelSalesordersubsub::where(['p_id' => $v['id']])->get();
                if ($suborder) {
                    $suborder = $suborder->toArray();
                } else {
                    $suborder = [];
                }
                $list['list'][$key]['suborder'][$k]['suborder'] = $suborder;
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 详情
     */
    public function getone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = ModelSalesorder::getone($id);
        $one = $one->toArray();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            if (!empty($one[0]['settle_company_id'])) {
                $stamp = TemplateContractsStamp::where(['company_id' => $one[0]['settle_company_id'],'status'=>1])->first();
                if ($stamp) {
                    $one[0]['stamp'] = $stamp->toArray();
                } else {
                    $one[0]['stamp']['seal_filepath'] = '';
                }
                $settle_company = SettleCompany::where(['id' => $one[0]['settle_company_id']])->first();
                if ($settle_company) {
                    $one[0]['settle_company'] = $settle_company->toArray();
                } else {
                    $one[0]['settle_company']['settle_company_name'] = '';
                }
            }

            if ($one[0]['suborder']) foreach ($one[0]['suborder'] as $key => $value) {
                $one[0]['suborder'][$key]['weight'] = mathfuncweight('div', $value['weight'], 10000, 4);
                $one[0]['suborder'][$key]['unit_price'] = mathfuncmoney('div', $value['unit_price'], 100, 2);
                $one[0]['suborder'][$key]['total'] = mathfuncmoney('div', $value['total'], 100, 2);


                $one[0]['suborder'][$key]['diff'] = mathfuncmoney('div', $value['diff'] ?? 0, 100, 2);
                $one[0]['suborder'][$key]['accrual'] = mathfuncmoney('div', $value['accrual'], 100, 2);
                $one[0]['suborder'][$key]['performance'] = mathfuncmoney('div', $value['performance'], 100, 2);
            }
            if (!empty($one[0]['warehouse_return_order'])) {
                $one[0]['warehouse_return_order'] = json_decode($one[0]['warehouse_return_order'],true);
            }


            return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
        }
    }

    /**
     * 编辑，只能编辑钢材的数量，件数，单价
     *
     *
     */
    public function dopostedit(Request $request)
    {
        $params = [
            'id',
            'order_number',
            'document_date',
            'bill_type',
            'business_type',
            'custom_id',
            'wagon_number',
            'driver_phone_number',
            'otherfee',
            'suborder',
            'remark'
        ];
        $req_data = $request->only($params);
        $validate = new Salesorder('edit');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $order_id = $req_data['id'];
        $one = ModelSalesorder::where('id', $order_id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        $mangerinfo = $this->mangerinfo;
        $cpid = $mangerinfo['cpid'] ?? 0;

        if (!empty($req_data['otherfee'])) {
            $otherfee = is_array($req_data['otherfee']) ? $req_data['otherfee'] : (is_array(json_decode($req_data['otherfee'], true)) ? json_decode($req_data['otherfee'], true) : []);
        } else {
            $otherfee = [];
        }

        //        $otherfeedata = [];
        $otherfeetotal = 0;
        $ValidateSub = new Saleorderfee('add');
        foreach ($otherfee as $fee) {
            $fee = is_array($fee) ? $fee : json_decode($fee, true);
            if (!$ValidateSub->check($fee)) {
                return response()->json(['code' => '001', 'msg' => $ValidateSub->getError()]);
            }
            $otherfeetotal = $otherfeetotal + $fee['price'];
        }

        $suborder = is_array($req_data['suborder']) ? $req_data['suborder'] : json_decode($req_data['suborder'], true);

        foreach ($suborder as $item) {
            $sales_sub_one = ModelSalesordersub::where('id', $item['id'])->first();
            if (!$sales_sub_one) {
                return response()->json(['code' => '001', 'msg' => '子订单不存在']);
            }

            $sales_sub_one = $sales_sub_one->toArray();
            if(empty($item['pieces']) || $item['pieces'] <= 0){
                return response()->json(['code' => '001', 'msg' => '子订单件数必须大于0']);
            }
            if(empty($item['weight']) || $item['weight'] <= 0){
                return response()->json(['code' => '001', 'msg' => '子订单重量必须大于0']);
            }
            if(empty($item['unit_price']) || $item['unit_price'] <= 0){
                return response()->json(['code' => '001', 'msg' => '子订单单价必须大于0']);
            }


            if ($item['pieces'] > $sales_sub_one['pieces']) {
                return response()->json(['code' => '001', 'msg' => '子订单件数不能大于原有件数']);
            }

            if ($sales_sub_one['produce_status'] == config('constants.produce_status.produced')) {
                return response()->json(['code' => '001', 'msg' => '已生成子订单不能生成']);
            }
        }

        $subvalidate = new Salesordersub('edit');
        foreach ($suborder as $item) {
            if (!$subvalidate->check($item)) {
                return response()->json(['code' => '001', 'msg' => $subvalidate->getError()]);
            }
        }

        DB::beginTransaction();
        try {
            $oldSubList = ModelSalesordersub::where([
                ['p_id', $req_data['id']],
                ['is_del', 1]
            ])->get()->toArray();
            //原订单金额
            $oldSubListTotalMoney = ModelSalesordersub::where([
                ['p_id', $req_data['id']],
                ['is_del', 1]
            ])->sum('total');

            $newSubList = $suborder;
            /***
             *  销货单 suborder item weight=total_weight
             *
            */
            if($oldSubList){
                foreach ($oldSubList as $key => $oldItem){
                    if(!isset($oldItem['total_weight'])){
                        $oldSubList[$key]['total_weight'] = $oldSubList[$key]['weight']??0;
                    }
                }
            }
            if($newSubList){
                foreach ($newSubList as $key => $newItem){
                    if(!isset($newItem['total_weight'])){
                        $newSubList[$key]['total_weight'] = $newSubList[$key]['weight']??0;
                    }
                }
            }

            if($otherfee)
            {
                foreach ($otherfee as $key => $fee)
                {
                     //修改其他费用订单数据
                    \App\Models\Order\Saleorderfee::where('id',$fee['id'])->update([
                        'price' => mathfuncmoney('mul', $fee['price'], 100),
                        'settlement_price' => mathfuncmoney('mul', $fee['settlement_price'], 100),
                        'remark' => isset($fee['remark']) ? strval($fee['remark']) : '',
                    ]);
                }
            }
            $SaleorderController = new SaleorderController($request);
            $incr_stock = $SaleorderController->incrDecrStockInSaleEdit($oldSubList,'incr','g');
            if($incr_stock['code'] != '000'){
                return response()->json($incr_stock);
            }
            $decr_stock = $SaleorderController->incrDecrStockInSaleEdit($newSubList,'decr');
            if($decr_stock['code'] != '000'){
                return response()->json($decr_stock);
            }
//            foreach ($oldSubList as $old) {
//                // old有，new有，编辑
//                if (in_array($old['id'], array_column($newSubList, 'id'))) {
//                    Stock::where(['id' => $old['stock_id']])->update([
//                        'can_use_pieces' => DB::raw('can_use_pieces + ' . $old['pieces']),
//                        'can_use_weight' => DB::raw('can_use_weight + ' . $old['weight']),
//                        'locked_pieces' => DB::raw('locked_pieces - ' . $old['pieces']),
//                        'locked_weight' => DB::raw('locked_weight - ' . $old['weight']),
//                    ]);
//
//                    foreach ($newSubList as $new) {
//                        if ($old['id'] == $new['id']) {
//                            Stock::where(['id' => $old['stock_id']])->update([
//                                'can_use_pieces' => DB::raw('can_use_pieces - ' . $new['pieces']),
//                                'can_use_weight' => DB::raw('can_use_weight - ' . mathfuncweight('mul', $new['weight'], 10000)),
//                                'locked_pieces' => DB::raw('locked_pieces + ' . $new['pieces']),
//                                'locked_weight' => DB::raw('locked_weight + ' . mathfuncweight('mul', $new['weight'], 10000)),
//                            ]);
//                        }
//                    }
//                } // old有，new无，删除
//                else {
//                    Stock::where(['id' => $old['stock_id']])->update([
//                        'can_use_pieces' => DB::raw('can_use_pieces + ' . $old['pieces']),
//                        'can_use_weight' => DB::raw('can_use_weight + ' . $old['weight']),
//                        'locked_pieces' => DB::raw('locked_pieces - ' . $old['pieces']),
//                        'locked_weight' => DB::raw('locked_weight - ' . $old['weight']),
//                    ]);
//                }
//            }

//            foreach ($newSubList as $new) {
//                // old无，new有，新增
//                if (empty($new['id'])) {
//                    Stock::where(['id' => $new['stock_id']])->update([
//                        'can_use_pieces' => DB::raw('can_use_pieces - ' . $new['pieces']),
//                        'can_use_weight' => DB::raw('can_use_weight - ' . mathfuncweight('mul', $new['weight'], 10000)),
//                        'locked_pieces' => DB::raw('locked_pieces + ' . $new['pieces']),
//                        'locked_weight' => DB::raw('locked_weight + ' . mathfuncweight('mul', $new['weight'], 10000)),
//                    ]);
//                }
//            }

            $beforeData = ModelSalesorder::where('id', $order_id)->with('suborder')->first();

            $data = [
                'document_date' => $req_data['document_date'],
                'bill_type' => $req_data['bill_type'],
                'business_type' => $req_data['business_type'],
                'wagon_number' => $req_data['wagon_number'] ?? '',
                'driver_phone_number' => $req_data['driver_phone_number'] ?? '',
                'remark' => $req_data['remark'],
                'update_at' => time(),
            ];
            ModelSalesorder::where('id', $order_id)->update($data);

            $sales_weight = $sales_amount = $sales_pieces = 0;
            foreach ($suborder as $item) {
                if(isset($item['can_use_weight'])){
                    unset($item['can_use_weight']);
                }

                if(isset($item['current_pieces'])){
                    unset($item['current_pieces']);
                }
                if(isset($item['can_use_pieces'])){
                    unset($item['can_use_pieces']);
                }


                $item['weight'] = mathfuncweight('mul', $item['weight'], 10000);
                $item['unit_price'] = mathfuncmoney('mul', $item['unit_price'], 100);
                $item['total'] = mathfuncmoney('mul', $item['total'], 100);
                $pieces = $item['pieces'] ?? 0;
                ModelSalesordersub::where('id', $item['id'])->update($item + ['update_at' => time()]);

                $sales_weight = $sales_weight + $item['weight'];
                $sales_amount = $sales_amount + $item['total'];
                $sales_pieces = $sales_pieces + $pieces;

                Saleimplementationsub::where([
                    'cpid' => $cpid,
                    'sales_id' => $item['id'],
                ])->update([
                    'sales_weight' => $item['weight'],
                    'sales_amount' => $item['total'],
                    'sales_pieces' => $item['pieces'],
                    'update_at' => time()
                ]);
            }

            Saleimplementation::where('order_number', $req_data['order_number'])->update([
                'sales_weight' => $sales_weight,
                'sales_amount' => $sales_amount,
                'sales_pieces' => $sales_pieces,
                'update_at' => time()
            ]);
            /***
             *  判断客户余额是否足够
             *
            */
            $custom_balance = Balance::where(['custom_id'=> $one['custom_id'], 'cpid' => $cpid])->value('balance');
            $before_sales_order_total = $custom_balance + $oldSubListTotalMoney;
            if($before_sales_order_total < $sales_amount){
                return response()->json(['code' => '001', 'msg' => '余额不足，编辑失败']);
            }

            //加余额
            Balance::where(['custom_id'=>$one['custom_id'],'cpid'=> $cpid])
                ->increment('balance', $oldSubListTotalMoney);
            //减余额
            Balance::where(['custom_id'=>$one['custom_id'],'cpid'=> $cpid])
                ->decrement('balance', $sales_amount);

            $afterData = ModelSalesorder::where('id', $order_id)->with('suborder')->first();
            EditLog::create([
                'cpid' => $cpid,
                'order_type' => 12,
                'order_sn_code' => $beforeData->document_number,
                'before_data' => json_encode($beforeData->toArray()),
                'after_data' => json_encode($afterData->toArray()),
                'editor_mid' => $mangerinfo['id'],
                'editor_realname' => $mangerinfo['realname'],
                'create_at' => time(),
            ]);

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '销货单编辑失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 申请报车单审核
     */
    public function dopostapply(Request $request)
    {
//        $params = ['id', 'settle_company_id', 'baochedan_type', 'is_yache', 'approve_id1'];
        $params = ['id',  'baochedan_type', 'is_yache', 'approve_id1'];
        $req_data = $request->only($params);
        $validate = new Salesorder('dopostapply');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $cpid = $this->mangerinfo['cpid'];
        $one = ModelSystemparam::where(['cpid' => $cpid, 'type' => 'fare'])->first();
        if ($one) {
            $fare = $one->value;
        } else {
            $fare = -10000;
        }

        $id = $req_data['id'];

        $one = ModelSalesorder::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            $one = $one->toArray();
        }

        $custom_id = $one['custom_id'];
        $customBalance = Balance::where('custom_id', $custom_id)->first();
        $customBalance = $customBalance->balance;
//        if(!(isset($req_data['settle_company_id']) && $req_data['settle_company_id'] > 0)){
//            return response()->json(['code' => '001', 'msg' => '请选择结算公司']);
//        }

        if(!(isset($req_data['baochedan_type']) && $req_data['baochedan_type'] > 0)){
            return response()->json(['code' => '001', 'msg' => '请选择报车单模版']);
        }
        if(!(isset($req_data['approve_id1']) && $req_data['approve_id1'] > 0)){
            return response()->json(['code' => '001', 'msg' => '请选择操盘账号']);
        }
        if($one['baochedan_status'] == 1)
        {
            return response()->json(['code' => '001', 'msg' => '报车单已经审批通过']);
        }

        if($one['baochedan_status'] == 2)
        {
            return response()->json(['code' => '001', 'msg' => '已有报车单审批']);
        }


        if ($customBalance/100 - $fare < 0) {
            //待审核
            $data = [
                'baochedan_status' => 2,
//                'settle_company_id' => $req_data['settle_company_id'],
                'baochedan_type' => $req_data['baochedan_type'],
                'is_yache' => $req_data['is_yache'],
                'is_copy' => 0,
                'approve_id1' => $req_data['approve_id1'],
                'update_at' => time(),
            ];
            $one = array_merge($one,$data);
            $one['sid'] = $one['id'];
            unset($one['id']);
            SalesCarReport::create($one);

        }
        else {
            //直接通过
            $data = [
                'baochedan_status' => 1,
//                'settle_company_id' => $req_data['settle_company_id'],
                'baochedan_type' => $req_data['baochedan_type'],
                'is_yache' => $req_data['is_yache'],
                'is_copy' => 1,
                'update_at' => time(),
            ];
        }


        ModelSalesorder::where('id', $id)->update($data);
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    public function hanledpass(Request $request)
    {
        $params = ['ids'];
        $req_data = $request->only($params);
        $validate = new Salesorder('hanledpass');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }
        $count = SalesCarReport::whereIn('id', $req_data['ids'])->where('baochedan_status','<>',2)->count();
        if($count>0){
            return response()->json(['code' => '001', 'msg' => '只有待审核的报车单才能审核']);
        }
        $ids = $req_data['ids'];
        foreach ($ids as $id) {
            $refund = SalesCarReport::where([
                'id' => $id
            ])->first();
            if (!$refund) {
                return response()->json(['code' => '001', 'msg' => '审核记录不存在']);
            }

            SalesCarReport::where([
                'id' => $id
            ])->update([
                'baochedan_status' => 1,
                'update_at' => time()
            ]);

            ModelSalesorder::where([
                'id' => $refund->sid
            ])->update([
                'baochedan_status' => 1,
                'update_at' => time()
            ]);

        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


    public function hanledrefuse(Request $request)
    {
        $params = ['ids'];
        $req_data = $request->only($params);
        $validate = new Salesorder('hanledrefuse');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }
        $count = SalesCarReport::whereIn('id', $req_data['ids'])->where('baochedan_status','<>',2)->count();
        if($count>0){
            return response()->json(['code' => '001', 'msg' => '只有待审核的报车单才能审核']);
        }

        $ids = $req_data['ids'];
        foreach ($ids as $id) {
            $refund = SalesCarReport::where([
                'id' => $id
            ])->first();


            if (!$refund) {
                return response()->json(['code' => '001', 'msg' => '审核记录不存在']);
            }

            SalesCarReport::where([
                'id' => $id
            ])->update([
                'baochedan_status' => 3,
                'update_at' => time()
            ]);

            ModelSalesorder::where([
                'id' => $refund->sid
            ])->update([
                'baochedan_status' => 3,
                'update_at' => time()
            ]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 上传仓库返单
     */
    public function uploadform(Request $request)
    {
        $params = ['id', 'warehouse_return_order','manger_id'];
        $req_data = $request->only($params);
        $validate = new Salesorder('uploadform');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }

        $id = $req_data['id'];
        $one = ModelSalesorder::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            $data = [
                'warehouse_return_order' => json_encode($req_data['warehouse_return_order']),
                'update_at' => time(),
            ];
            ModelSalesorder::where('id', $id)->update($data);
            /**
             * 审核通过后，销售上传了仓库返单，操盘点击查看的时候，
             * 这个时候是要有仓库返单的 2025.04.19 王丹娜
             *
             *
            */
            SalesCarReport::where('sid', $id)->update($data);
            /***
             * is_copy 0 数据审核，baochedan_status=1 审核通过
             *
            */
            if($one->is_copy == 0 && $one->baochedan_status == '1')
            {
                //站内信给采购
                Notice::create([
                    'cpid'=>$this->mangerinfo['cpid'],
                    'manger_id'=>$req_data['manger_id'],
                    'utype' => '6',
                    'order_number'=>$one->order_number,
                    'contents'=>'该订单:'.$one->order_number.'，有一笔未收款的报车单，需线下沟通提醒业务员收款',
                    'status'=>1,
                    'create_at'=>time(),
                    'update_at'=>time(),
                ]);
            }
            return response()->json(['code' => '000', 'msg' => '操作成功']);
        }
    }

    /**
     * 删除
     * 删除的子订单，需要将对应的销售子订单回滚
     */
    public function dodel(Request $request)
    {
        $id = $request['id'];
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $one = ModelSalesorder::where('id', $id)->first();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            $one = $one->toArray();
        }

        DB::beginTransaction();
        try {
            $suborder = is_array($request['suborder']) ? $request['suborder'] : json_decode($request['suborder'], true);
            if ($suborder) {
                $rollback_custom = $one["custom_id"];//回退客户id
                $rollback_balance = 0; //回退余额
                $produce_status = 1;

                $total_sales_weight = 0;
                $total_sales_amount = 0;
                $total_sales_pieces = 0;
                $sale_implementation_id = 0;
                /***
                 *  虚拟单，发货单时扣库存。删除时，返库存 2025.07.08
                 *  涉及删除，先处理库存
                 */
                $ModelSaleorder = ModelSaleorder::where(['order_number'=>$one["order_number"],'is_del'=>'1','cpid'=>$cpid])->first();
                if($ModelSaleorder->order_type == '2'){
                    $SaleorderController = new SaleorderController($request);
                    $ModelSalesordersub_stock = ModelSalesordersub::where(['id'=>$suborder,'is_del'=>'1'])->get()->toArray();
                    foreach ($ModelSalesordersub_stock as $key=>$stock_item){
                        $ModelSalesordersub_stock[$key]['total_weight'] = $stock_item['weight'];
                    }
                    //必须有 total_weight pieces stock_id
                    $incrStock = $SaleorderController->incrDecrStockInSaleEdit($ModelSalesordersub_stock,'incr','g');
                    if($incrStock['code'] != '000'){
                        return response()->json($incrStock);
                    }
                }

                foreach ($suborder as $item) {
                    $data = [
                        'is_del' => config('constants.is_del.yes'),
                        'update_at' => time(),
                    ];
                    ModelSalesordersub::where('id', $item)->update($data);

                    $sales_one_sub = ModelSalesordersub::where('id', $item)->first()->toArray();
                    $sale_one_sub = ModelSaleordersub::where('id', $sales_one_sub['sale_id'])->first()->toArray();
                    /***
                     *  销售订单 可以修改子订单单价发货，导致销售子订单和发货子订单 金额不一致，销货单删除时，以销货金额为准
                     *
                    */
                    $rollback_balance+= $sales_one_sub["total"];
                    if (
                        $sales_one_sub['pieces'] == $sale_one_sub['pieces']
                        || $sales_one_sub['pieces'] == $sale_one_sub['produce_pieces']
                    ) {
                        $data = [
                            'produce_status' => config('constants.produce_status.not_produced'),
                            'produce_pieces' => 0,
                            'update_at' => time()
                        ];
                        $produce_status = 1;
                    } else {
                        $data = [
                            'produce_status' => config('constants.produce_status.produceing'),
                            'produce_pieces' => $sale_one_sub['produce_pieces'] - $sales_one_sub['pieces'],
                            'update_at' => time()
                        ];
                        $produce_status = 2;
                    }
                    //回滚已生成的重量
                    $data['produce_total_weight'] = $sale_one_sub['produce_total_weight'] - $sales_one_sub['weight'];
                    ModelSaleordersub::where('id', $sales_one_sub['sale_id'])->update($data);

                    if($sales_one_sub['qianyi_total_weight'] > 0)
                    {
                        //回滚库存从已锁到可用
                        Stock::where(['id' => $sales_one_sub['stock_id']])->update([
                            'locked_weight' => DB::raw('locked_weight - ' . $sales_one_sub['qianyi_total_weight']),
                            'can_use_weight' => DB::raw('can_use_weight + ' . $sales_one_sub['qianyi_total_weight']),
                        ]);
                    }

                    //回退销售订单执行表.销货单数据 $item=sales_id
                    $Saleimplementationsub = Saleimplementationsub::where(['is_del'=>1,'sales_id'=>$item])->first();
                    if($Saleimplementationsub){
                        $Saleimplementationsub->sales_weight -= $sales_one_sub['weight'];
                        $Saleimplementationsub->sales_amount -= $sales_one_sub['total'];
                        $Saleimplementationsub->sales_pieces -= $sales_one_sub['pieces'];
                        $Saleimplementationsub->save();

                        $total_sales_weight += $sales_one_sub['weight'];
                        $total_sales_pieces += $sales_one_sub['pieces'];
                        $total_sales_amount += $sales_one_sub['total'];
                        if($sale_implementation_id === 0){
                            $sale_implementation_id = $Saleimplementationsub['p_id'];
                        }
                    }
                }

                if($sale_implementation_id > 0){
                    $Saleimplementation = Saleimplementation::where('id',$sale_implementation_id)->first();
                    $Saleimplementation->sales_weight -= $total_sales_weight;
                    $Saleimplementation->sales_pieces -= $total_sales_pieces;
                    $Saleimplementation->sales_amount -= $total_sales_amount;
                    $Saleimplementation->save();
                }

                \App\Services\Balance\Balance::SaleRefund($rollback_custom,$cpid,$rollback_balance,$manger_id,"2");
                ModelSaleorder::where('order_number', $one['order_number'])->update(['produce_status' => $produce_status]);
            }
            $sales_list_sub = ModelSalesordersub::where('p_id', $id)->get();
            foreach ($sales_list_sub as $item) {
                if ($item->is_del == config('constants.is_del.yes')) {
                    $data = [
                        'is_del' => config('constants.is_del.yes'),
                        'update_at' => time(),
                    ];
                    ModelSalesorder::where('id', $id)->update($data);
                    break;
                }
            }

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '删除失败' . $e->getMessage()]);
        }

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    public function doposteditsuborder(Request $request) {
        $params = ['id', 'diff'];
        $req_data = $request->only($params);
        $validate = new Salesorder('doposteditsuborder');
        if (!$validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $validate->getError()]);
        }
        $cpid = $this->mangerinfo['cpid'];

        $SalesOrderSub = ModelSalesordersub::where('id',$req_data['id'])->first();
        if(!$SalesOrderSub)
        {
            return response()->json(['code' => '001', 'msg' => '参数有误']);
        }

        //获取主订单的单据日期
        $document_date = ModelSalesorder::where('id',$SalesOrderSub->p_id)->value('document_date');
        $document_date = date('Y-m-d',$document_date);
        //增加校验如果操盘修改过当日定价  不允许在继续修改差额
        //如果type=1并且create_at 和$document_date 在同一天  或者type=2 和$document_date  start_time和end_time之间则不允许修改
        $salecover = SaleCover::query()
            ->where('is_del', 1)
            ->where('cpid', $cpid)
            ->where(function($query) use ($document_date) {
                $query->where(function($q) use ($document_date) {
                    $q->where('type', 1)
                        ->whereRaw('DATE(FROM_UNIXTIME(create_at)) = ?', [$document_date]);
                })->orWhere(function($q) {
                    $q->where('type', 2)
                        ->whereRaw('create_at BETWEEN start_time AND end_time');
                });
            })
            ->first();
        if($salecover)
        {
            return response()->json(['code' => '001', 'msg' => '操盘覆盖定价，不允许修改']);
        }

        //重新计算业绩
        $diff_cent = SaleorderController::amountTransformIntoCent($req_data['diff']);
        $saleorder = new SaleorderController($request);

        $performance = $saleorder->performance($SalesOrderSub['accrual'],$SalesOrderSub['weight'],$diff_cent);
        //$diff = mathfuncmoney('mul', $req_data['diff'], 100, 2);
        ModelSalesordersub::where('id', $req_data['id'])
            ->update(['diff' => $diff_cent,'performance'=>$performance]);
        //
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     *  生成销货单节点,检查销售订单是否已经完成
     *
    */
    public function checkDelivery($data=[]){
        if(empty($data['id'])){
            return false;
        }
        $Saleordersub = ModelSaleordersub::where(['p_id'=>$data["id"],"is_del"=>"1"])->get();
        if($Saleordersub->isEmpty()){
            return false;
        }
        $finish = true;
        foreach ($Saleordersub as $item){
            // if($item["produce_pieces"] == $item["pieces"]){
            //     continue;
            // }else{
            //     $diff = $item["produce_pieces"];
            //     foreach ($data["suborder"] as $sub_item){
            //         if($item["stock_id"] == $sub_item["stock_id"]){
            //             $diff += $sub_item["pieces"];
            //         }
            //     }
            //     if($diff != $item["pieces"]){
            //         $finish = false;
            //     }
            // }
            //虚拟性质 销售订单 无法完成
            if($item["archive_type"] == '4'){
                $finish = false;
                break;
            }
            if($item["produce_pieces"] < $item["pieces"]){
                $finish = false;
                break;
            }
            if($item["produce_pieces"] >= $item["pieces"]){
                continue;
            }
        }
        return $finish;
    }


    /**
     * 列表
     */
    public function getcarreportlist(Request $request)
    {
        $memberinfo = $this->mangerinfo;
        $isgetall = $request->isgetall ?? 0;
        $list = SalesCarReport::getList($request, $memberinfo, $isgetall);
        if ($list['list']) foreach ($list['list'] as $key => $value) {
            foreach ($value['suborder'] as $k => $v) {
                $list['list'][$key]['suborder'][$k]['weight'] = mathfuncweight('div', $v['weight'], 10000, 4);
                $list['list'][$key]['suborder'][$k]['unit_price'] = mathfuncmoney('div', $v['unit_price'], 100, 2);
                $list['list'][$key]['suborder'][$k]['total'] = mathfuncmoney('div', $v['total'], 100, 2);

                $list['list'][$key]['suborder'][$k]['diff'] = mathfuncmoney('div', $v['diff'] ?? 0, 100, 2);
                $list['list'][$key]['suborder'][$k]['accrual'] = mathfuncmoney('div', $v['accrual'], 100, 2);
                $list['list'][$key]['suborder'][$k]['performance'] = mathfuncmoney('div', $v['performance'], 100, 2);

                $suborder = ModelSalesordersubsub::where(['p_id' => $v['id']])->get();
                if ($suborder) {
                    $suborder = $suborder->toArray();
                } else {
                    $suborder = [];
                }
                $list['list'][$key]['suborder'][$k]['suborder'] = $suborder;
            }
        }
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 詳情
     */
    public function getcarreportone(Request $request)
    {
        $id = $request->id ?? 0;
        $one = SalesCarReport::getone($id);
        $one = $one->toArray();
        if (!$one) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        } else {
            if (!empty($one[0]['settle_company_id'])) {
                $stamp = TemplateContractsStamp::where(['company_id' => $one[0]['settle_company_id'],'status'=>1])->first();
                if ($stamp) {
                    $one[0]['stamp'] = $stamp->toArray();
                } else {
                    $one[0]['stamp']['seal_filepath'] = '';
                }
                $settle_company = SettleCompany::where(['id' => $one[0]['settle_company_id']])->first();
                if ($settle_company) {
                    $one[0]['settle_company'] = $settle_company->toArray();
                } else {
                    $one[0]['settle_company']['settle_company_name'] = '';
                }
            }
            if(!empty($one[0]['warehouse_return_order'])){
                $one[0]['warehouse_return_order'] = json_decode($one[0]['warehouse_return_order'],true);
            }
            if ($one[0]['suborder']) foreach ($one[0]['suborder'] as $key => $value) {
                $one[0]['suborder'][$key]['weight'] = mathfuncweight('div', $value['weight'], 10000, 4);
                $one[0]['suborder'][$key]['unit_price'] = mathfuncmoney('div', $value['unit_price'], 100, 2);
                $one[0]['suborder'][$key]['total'] = mathfuncmoney('div', $value['total'], 100, 2);


                $one[0]['suborder'][$key]['diff'] = mathfuncmoney('div', $value['diff'] ?? 0, 100, 2);
                $one[0]['suborder'][$key]['accrual'] = mathfuncmoney('div', $value['accrual'], 100, 2);
                $one[0]['suborder'][$key]['performance'] = mathfuncmoney('div', $value['performance'], 100, 2);
            }



            return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $one]);
        }
    }
}
